#!/usr/bin/env python
# -*- coding:utf-8 -*-
# -----------------
#  Authur: 王荣雯
#　Create date: '2017.7.18' ''
# -----------------
import maya.cmds as cmds
import cPickle,os

import settings
reload(settings)
from maya_utils import plugin_utils

class AtomFileUtils(object):
    def __init__(self, ctrl_file, atom_file):
        self.__ctrl_file = ctrl_file
        self.__atom_file = atom_file

    def get_ctrl_attr_list(self, ctrl_list):
        exp_ctrl_attr_dict = {}
        exp_attr_list = []
        key_list = []
        for ctrl in ctrl_list:
            all_attr_list = cmds.listAttr(ctrl, k=1)
            for attr in all_attr_list:
                clear, key = self.del_anim_keys(ctrl, attr)
                if not clear:
                    exp_attr_list.append(attr)
                key_list.append(key)
            if exp_attr_list:
                exp_ctrl_attr_dict[ctrl] = exp_attr_list
        return exp_ctrl_attr_dict, key_list

    def del_anim_keys(self, ctrl, attr):
        need_clear = True
        set_key = True
        keepAttr = settings.NEED_KEEP_ATTR
        delAttr = settings.NEED_REMOVE_ATTR

        if attr in delAttr:
            need_clear = True

        elif attr in keepAttr:
            cmds.setKeyframe(ctrl, at=attr, t=[0], v=0)
            need_clear = False

        else:
            ani_time = cmds.keyframe(ctrl, at=attr, q=1, tc=1)

            if ani_time:
                value = cmds.keyframe(ctrl, at=attr, q=1, vc=1, t=(ani_time[0], ani_time[-1]))
                for i in value:
                    if i != 0:
                        need_clear = False
                        break
            else:
                value = cmds.getAttr(ctrl+'.'+attr)
                if value:
                    result = self.promptDialog_no_key(ctrl, attr)
                    if result == u'自动设置':
                        cmds.setKeyframe(ctrl, at=attr, t=[0], v=value)
                        need_clear = False
                        set_key = True
                    else:
                        set_key = False
                    print set_key

        if need_clear:
            cmds.cutKey(ctrl, at=attr)

        return need_clear, set_key

    def promptDialog_no_key(self, ctrl, attr):
        result = cmds.confirmDialog( title=u'警告',
                                     message=u'%s.%s 未设置关键帧，点击"自动设置"在第0帧设置，点击"手动设置"忽略'%(ctrl, attr),
                                     button=[u'自动设置',u'手动设置'], defaultButton=u'自动设置',
                                     cancelButton=u'手动设置', dismissString=u'手动设置' )
        return result

    def promptDialog_warning(self, message):
        cmds.confirmDialog( title=u'警告',
                                     message=message,
                                     button=[u'确定'] )

    def export_ctrl_list(self, ctrl_list):
        with file(self.__ctrl_file, 'w') as f:
            cPickle.dump(ctrl_list, f)

    def import_ctrl_list(self):
        with file(self.__ctrl_file) as f:
            ctrl_list = cPickle.load(f)
            return ctrl_list

    def export_atom(self):
        cmds.file(self.__atom_file, f=1, typ="atomExport", es=1)

    def import_atom(self):
        cmds.file(self.__atom_file, i=1, typ="atomImport")

def export_import_ani(imex, ch_name, layer_name):
    plugin_utils.checkAndLoadPlugin('atomImportExport')
    path = settings.ANIM_FILE_PATH
    file_path = os.path.join(path, ch_name)
    ctrl_file = os.path.join(file_path, layer_name + '.ctrl')
    atom_file = os.path.join(file_path, layer_name + '.atom')
    atom_file_utils = AtomFileUtils(ctrl_file, atom_file)

    if imex == 'ex':
        sel_ctrl_list = cmds.ls(sl=1)
        if sel_ctrl_list:

            if not os.path.isdir(file_path):
                os.mkdir(file_path)

            ctrl_list, key_list = atom_file_utils.get_ctrl_attr_list(sel_ctrl_list)
            print key_list

            if False in key_list:
                atom_file_utils.promptDialog_warning(u'有属性未设置关键帧，不能导出数据')

            else:
                atom_file_utils.export_ctrl_list(ctrl_list)
                atom_file_utils.export_atom()

        else:
            atom_file_utils.promptDialog_warning(u'需要选择全部控制器')

    elif imex == 'im':
        ctrl_list = atom_file_utils.import_ctrl_list()
        cmds.select(ctrl_list,r=1)

def test():
    export_import_ani('ex', 'bocai', 'walk')